import { createEntity } from '../database/middleware';
import { listEntitiesThroughRelationsPaginated, listEntities, storeLoadById } from '../database/middleware-loader';
import { BUS_TOPICS } from '../config/conf';
import { notify } from '../database/redis';
import { ENTITY_TYPE_VULNERABILITY } from '../schema/stixDomainObject';
import { ABSTRACT_STIX_DOMAIN_OBJECT } from '../schema/general';
import { RELATION_HAS } from '../schema/stixCoreRelationship';
import { ENTITY_SOFTWARE } from '../schema/stixCyberObservable';

export const findById = (context, user, vulnerabilityId) => {
  return storeLoadById(context, user, vulnerabilityId, ENTITY_TYPE_VULNERABILITY);
};

export const findAll = (context, user, args) => {
  return listEntities(context, user, [ENTITY_TYPE_VULNERABILITY], args);
};

export const addVulnerability = async (context, user, vulnerability) => {
  const created = await createEntity(context, user, vulnerability, ENTITY_TYPE_VULNERABILITY);
  return notify(BUS_TOPICS[ABSTRACT_STIX_DOMAIN_OBJECT].ADDED_TOPIC, created, user);
};

export const softwarePaginated = async (context, user, vulnerabilityId, opts) => {
  return listEntitiesThroughRelationsPaginated(context, user, vulnerabilityId, RELATION_HAS, ENTITY_SOFTWARE, true, opts);
};
